<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item v-if="isShowQuery" label="选择患者" prop="itemName" style="float: left">
          <bed-vs-patient-into-select :bed-blank="'Y'" :clearable="true"
                                      :org-id="userInfo.orgId"
                                      :visit-id="queryParams.visitId" :ward-code="currentSelectDept" class="width-120"
                                      @bed-change="bedChange"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="packItemName">
          <el-input
            v-model="queryParams.itemName"
            clearable
            placeholder="请输入项目名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="收费项目名称" prop="itemName">
          <el-input
            v-model="queryParams.itemName"
            clearable
            placeholder="请输入收费项目名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          plain
          type="primary"
          @click="handleAdd"
        >
          <template
            #icon>
            <i-ep-plus/>
          </template>
          录入费用
        </el-button>
      </el-col>
    </el-row>

    <el-table v-adaptive="340" :border="true" :data="nurseAutoItemList" :header-cell-style="$headerCellStyle"
              :span-method="objectSpanMethod" :stripe="true" highlight-current-row>
      <el-table-column :align="'center'" label="项目名称" prop="packItemName"/>
      <el-table-column :align="'center'" label="收费项目名称" prop="itemName"/>
      <el-table-column :align="'center'" label="规格" prop="itemSpec" width="100"/>
      <el-table-column :align="'center'" label="单价" prop="itemPrice" width="100">
        <template #default="scope">
          <span class="ys-css">{{ parseFloat((scope.row.itemPrice).toString()).toFixed(2) || '/' }}</span>元
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="数量" prop="amount" width="100"/>
      <el-table-column :align="'center'" label="单位" prop="unitsName" width="100"/>
      <el-table-column :align="'center'" label="应付费用" prop="costs" width="100">
        <template #default="scope">
          <span class="ys-css">{{ parseFloat((scope.row.costs).toString()).toFixed(2) || '/' }}</span>元
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="开单科室" prop="applyDeptName" sortable width="100"/>
      <el-table-column :align="'center'" label="开单护士" prop="applyUserName" sortable width="100"/>
      <el-table-column :align="'center'" label="执行科室" prop="implementDeptName" sortable width="100"/>
      <el-table-column :align="'center'" label="执行人员" prop="implementUserName" sortable width="100"/>
      <el-table-column :align="'center'" label="创建人" prop="createByName" sortable width="100"/>
      <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="100">
        <template #default="scope">
          <el-button
            type="danger"
            @click="handleDelete(scope.row)"
          >
            <template #icon>
              <i-ep-delete/>
            </template>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改患者固定费用配置对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="30%">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目名称" prop="packItemName">
          <el-input v-if="isShow" v-model="form.packItemName"
                    @focus="isShowItemNameFocus()">
          </el-input>
          <automatic-completion
            v-else ref="itemAutomatic"
            v-model="form.packItemName" :dict-array="dictArray"
            :table-body-list="tableBodyList"
            :table-head-list="tableHeadList"
            :title="itemTitle"
            :width="900"
            style="width: 100%"
            @itemNameInput="itemNameInput"
            @row-click="rowClick"
          />
        </el-form-item>
        <el-form-item label="规格" prop="itemSpec">
          <el-input v-model="form.itemSpec" :disabled="true"/>
        </el-form-item>
        <el-form-item label="单位" prop="units">
          <el-select v-model="form.units" :disabled="true">
            <el-option
              v-for="dict in dictDataMap['spec_unit']"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="itemPrice">
          <el-input v-model="form.itemPrice" :disabled="true" placeholder="单价">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入数量" @blur="amountBlur"/>
        </el-form-item>
        <el-form-item label="应付费用" prop="costs">
          <el-input v-model="form.costs" :disabled="true" placeholder="应付费用">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="开单科室" prop="applyDept">
          <dept-list v-model="form.applyDept" :clinic-vs-visit-str="'1,2'" :dept-id="form.applyDept"
                     :org-id="userInfo.orgId" :placeholder="'请选择开单科室'"
                     style="width: 100%" @dept-change="applyDeptChange"
          />
        </el-form-item>
        <el-form-item label="开单人" prop="applyUser">
          <el-select v-model="form.applyUser" placeholder="请选择"
                     style="width: 100%" @change="doctorChange($event, item, '4')">
            <el-option v-for="item in orgVsDoctorList" :key="item.userId" :label="item.nickName"
                       :value="item.userId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="执行科室" prop="implementDept">
          <dept-list v-model="form.implementDept" :clinical-sign-str="'3'" :dept-id="form.implementDept"
                     :org-id="userInfo.orgId" :placeholder="'请选择执行科室'"
                     style="width: 100%" @dept-change="implementDeptChange"
          />
        </el-form-item>
        <el-form-item label="执行人" prop="implementUser">
          <el-select v-model="form.implementUser" placeholder="请选择"
                     style="width: 100%" @change="nurseChange($event, item, '2')">
            <el-option v-for="item in orgVsNurseList" :key="item.userId" :label="item.nickName"
                       :value="item.userId"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                  <el-button type="primary" @click="submitForm">确 定</el-button>
                  <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name: "NurseAutoItem"
}
</script>

<script lang="ts" setup>
import {
  addNurseAutoItem,
  delNurseAutoItem,
  listNurseAutoItem,
  updateNurseAutoItem
} from "@/api/nurse/nurseAutoItem";

import {useDictStoreHook} from "@/store/modules/dict";
import {getDeptVsUserInfo} from "@/api/system/dept.ts";
import {useUserStoreHook} from "@/store/modules/user.ts";
import {clinicTableHeadList, jsonStrInObj} from "@/utils/autoComplete.ts";
import {autoBuildQuery} from "@/api/base/clinicItemDict.ts";
import {positiveNumberNotNull} from "@/utils/myRules.ts"

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit'))

const {proxy} = getCurrentInstance() as any;

const props = defineProps({
  showParams: {
    type: Object,
    default: {}
  },
  isShowQuery: {
    type: Boolean,
    default: true
  }
})

const currentSelectDept = proxy.$currentSelectDept
// 选中科室下医生list
const orgVsDoctorList = ref<any>([])
// 选中执行科室下护士list
const orgVsNurseList = ref<any>([])
const formRef = ref();
const queryParamsRef = ref()
const nurseAutoItemList = ref([]);
const itemAutomatic = ref();
const open = ref(false);
const showSearch = ref(true);
const title = ref("");
// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(clinicTableHeadList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])
const autoForm = ref<any>({
  clinicItemName: "",
  itemInfo: "",
  orgId: userInfo.orgId,
  isFiltrationContrastExist: true,
  notInSelect: [],
});
const form = ref<any>({
  visitId: "",
  patientId: "",
  clinicItemId: "",
  packItemName: "",
  itemName: "",
  itemSpec: "",
  units: "",
  itemPrice: "",
  amount: 0,
  costs: "",
  priceId: "",
  remarks: "",
  chargeCoefficient: "",
  unitsName: "",
  orgId: userInfo.orgId,
  applyDept: props.showParams.deptStayed,
  applyUser: props.showParams.doctorInCharge,
  applyDeptName: props.showParams.deptStayedName,
  applyUserName: props.showParams.doctorInChargeName,
  implementDept: props.showParams.wardCode,
  implementUser: props.showParams.dutyNurse,
  implementDeptName: props.showParams.wardCodeName,
  implementUserName: props.showParams.dutyNurseName,
})
const queryParams = ref<any>({
  visitId: "",
  patientId: "",
  clinicItemId: "",
  packItemName: "",
  itemName: "",
  itemSpec: "",
  units: "",
  itemPrice: "",
  costs: "",
  priceId: "",
  applyDept: "",
  applyUser: "",
  implementDept: "",
  implementUser: "",
  remarks: "",
  chargeCoefficient: "",
  unitsName: "",
  applyDeptName: "",
  applyUserName: "",
  implementDeptName: "",
  implementUserName: "",
})
const rules = ref({
  amount: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  applyDept: [
    {
      required: true, message: "开单科室不能为空", trigger: "blur"
    }
  ],
  packItemName: [
    {
      required: true, message: "项目不能为空", trigger: "change"
    }
  ],
  applyUser: [
    {
      required: true, message: "开单人不能为空", trigger: "blur"
    }
  ],
  implementDept: [
    {
      required: true, message: "执行科室不能为空", trigger: "blur"
    }
  ],
  implementUser: [
    {
      required: true, message: "执行人不能为空", trigger: "blur"
    }
  ],
})

// 开单科室下拉选择事件
function applyDeptChange(value: any) {
  form.value.applyDept = value.deptId
  getOrgVsDoctorListFun()
}

// 开单人查询
function getOrgVsDoctorListFun() {
  if (form.value.applyDept) {
    getDeptVsUserInfo({deptId: form.value.applyDept}).then((res: resType) => {
      orgVsDoctorList.value = res.data
    })
  } else {
    orgVsDoctorList.value = []
  }
}

// 执行科室下拉选择事件
function implementDeptChange(value: any) {
  form.value.implementDept = value.deptId
  getOrgVsNurseListFun()
}


// 执行人人查询
function getOrgVsNurseListFun() {
  if (form.value.implementDept) {
    getDeptVsUserInfo({deptId: form.value.implementDept}).then((res: resType) => {
      orgVsNurseList.value = res.data
    })
  } else {
    orgVsNurseList.value = []
  }
}

/**
 * 父组件加载初始化方法
 */
function initOpen(obj: any) {
  queryParams.value.visitId = obj.visitId;
  queryParams.value.patientId = obj.patientId;
  getList()
}


/** 查询患者固定费用配置列表 */
function getList() {
  if (queryParams.value.visitId) {
    listNurseAutoItem(queryParams.value).then((response: any) => {
      nurseAutoItemList.value = response.data;
      console.log("nurseAutoItemList.value", nurseAutoItemList.value)
    });
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    nurseAutoItemId: "",
    visitId: queryParams.value.visitId,
    patientId: queryParams.value.patientId,
    clinicItemId: "",
    packItemName: "",
    itemName: "",
    itemSpec: "",
    units: "",
    itemPrice: "",
    amount: 1,
    costs: "",
    priceId: "",
    orgId: userInfo.orgId,
    applyDept: props.showParams.deptStayed,
    applyUser: props.showParams.doctorInCharge,
    applyDeptName: props.showParams.deptStayedName,
    applyUserName: props.showParams.doctorInChargeName,
    implementDept: props.showParams.wardCode,
    implementUser: props.showParams.dutyNurse,
    implementDeptName: props.showParams.wardCodeName,
    implementUserName: props.showParams.dutyNurseName,
  }
  nextTick(() => {
    formRef.value.resetFields()
  })
}

/**
 * 切换患者select 点击事件
 * @param obj
 */
function bedChange(obj) {
  queryParams.value.visitId = obj.visitId;
  queryParams.value.patientId = obj.patientId;
  getList()
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  // proxy.resetForm("queryRef");
  handleQuery();
}

/** 清空 */
function empty() {
  queryParamsRef.value.resetFields()
  nurseAutoItemList.value = []
}

/** 新增按钮操作 */
function handleAdd() {
  open.value = true;
  reset();
  getOrgVsDoctorListFun()
  getOrgVsNurseListFun()
  title.value = "录入患者固定费用";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true;
  reset();
  // const _nurseAutoItemId = row.nurseAutoItemId
  // getNurseAutoItem(_nurseAutoItemId).then((response: any) => {
  //     form.value = response.data;
  form.value = row;
  getOrgVsDoctorListFun()
  getOrgVsNurseListFun()
  title.value = "修改患者固定费用配置";
  // });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      if (form.value.nurseAutoItemId != "") {
        updateNurseAutoItem(form.value).then(() => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
        });
      } else {
        addNurseAutoItem(form.value).then(() => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _nurseAutoItemIds = row.nurseAutoItemId
  ElMessageBox.confirm('是否确认删除患者固定费用配置编号为"' + _nurseAutoItemIds + '"的数据项？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delNurseAutoItem(_nurseAutoItemIds).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/nurseAutoItem/export', {
    ...queryParams.value
  }, `nurseAutoItem_${new Date().getTime()}.xlsx`)
}

/** 项目名称自动补全检索 */
function itemNameInput(itemName: String) {
  autoForm.value.itemInfo = itemName;
  getListClinicItemDict();

}

/** 自动补全后台查询 */
function getListClinicItemDict() {
  if (autoForm.value.itemInfo) {
    // form.value.notInSelect = ['A', 'B', 'F', 'C', 'D', 'E', 'F', 'G', 'H']
    autoForm.value.notInSelect = ["A", "B"];
    autoForm.value.orgId = userInfo.orgId;
    // 是否过滤已存在的项目标记
    autoForm.value.isFiltrationContrastExist = true;
    autoBuildQuery(autoForm.value).then((res) => {
      tableBodyList.value = res.data;
      // 打开自动补全弹出框
      itemAutomatic.value.init();
    });
  } else {
    tableBodyList.value = [];
  }
}

/** 项目列表行点击事件 */
function rowClick(row: any) {
  itemAutomatic.value.closePopover();
  isShow.value = true
  form.value.clinicItemId = row.clinicItemId;
  form.value.packItemName = row.itemName;
  form.value.itemSpec = row.itemSpec;
  form.value.itemClass = row.itemClass;
  autoForm.value.clinicItemName = row.itemName;
  const subTotal = row.subTotal ? row.subTotal : 0;
  form.value.itemPrice = subTotal.toFixed(2);
  form.value.costs = (subTotal * form.value.amount).toFixed(2);
  tableBodyList.value = [];
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
let isShow = ref(true);

function isShowItemNameFocus() {
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.packItemName)
    itemAutomatic.value.focusInput()
  })
}


/**
 * 开单数量input焦点消失时间
 */
function amountBlur() {
  form.value.costs = (Number(form.value.amount) * Number(form.value.itemPrice)).toFixed(2);
}

/** 表格合并列和行 */
function objectSpanMethod({row, column, rowIndex, columnIndex}) {
  if (columnIndex === 0) {
    const _row = flitterData(nurseAutoItemList.value, columnIndex).one[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col,
    };
  }
}


/**合并表格的第一列，处理表格数据 */
function flitterData(arr, columnIndex) {
  let spanOneArr: any = [];
  let concatOne = 0;
  arr.forEach((item, index) => {
    if (index === 0) {
      spanOneArr.push(1);
    } else {
      //注意这里的quarterly是表格绑定的字段，根据自己的需求来改
      if (columnIndex === 0) {
        if (item.clinicItemId === arr[index - 1].clinicItemId) {
          //第一列需合并相同内容的判断条件
          spanOneArr[concatOne] += 1;
          spanOneArr.push(0);
        } else {
          spanOneArr.push(1);
          concatOne = index;
        }
      }
    }
  });
  return {
    one: spanOneArr,
  };
}

getList();

defineExpose({
  initOpen,
  empty
})
</script>
